package com.tjcm.tjcminspectmanager;

import java.io.IOException;
import java.util.Date;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import cn.emagsoftware.ui.dialog.DialogManager;
import cn.emagsoftware.ui.staticmanager.StaticManager;
import cn.emagsoftware.util.DateUtilities;
import cn.emagsoftware.util.LogManager;

import com.tjcm.tjcminspectmanager.manager.GPSManager;
import com.tjcm.tjcminspectmanager.model.PlanItem;
import com.tjcm.tjcminspectmanager.model.User;

public class PlanDetailActivity extends BaseActivity
{

    private PlanItem         item        = null;
    private User             user        = null;

    private LocationManager  mgr         = null;
    private LocationListener listener    = null;

    private TextView         currenttime = null;
    private TextView         longitude   = null;
    private TextView         latitude    = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        if (!LoginActivity.IS_APP_RUNNING)
        {
            StaticManager.restartAppWhenDalvikRecycled(this, LoginActivity.class);
            return;
        }
        Intent intent = getIntent();
        item = (PlanItem) intent.getSerializableExtra("PLAN_ITEM");
        user = (User) intent.getSerializableExtra("USER");
        setContentView(R.layout.plandetail);

        mgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        TextView planname = (TextView) findViewById(R.id.planname);
        TextView starttime = (TextView) findViewById(R.id.starttime);
        TextView endtime = (TextView) findViewById(R.id.endtime);
        currenttime = (TextView) findViewById(R.id.currenttime);
        longitude = (TextView) findViewById(R.id.longitude);
        latitude = (TextView) findViewById(R.id.latitude);
        TextView processtimes = (TextView) findViewById(R.id.processtimes);
        TextView sbname = (TextView) findViewById(R.id.sbname);
        Button deal = (Button) findViewById(R.id.deal);
        Button back = (Button) findViewById(R.id.back);

        planname.setText(item.planName);
        starttime.setText(item.startTime);
        endtime.setText(item.endTime);
        processtimes.setText(item.processTimes);
        sbname.setText(item.sbName.split(",")[0]);
        deal.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                deal(true);
            }
        });
        back.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                finish();
            }
        });
        if (savedInstanceState != null)
        {
            boolean isDealing = savedInstanceState.getBoolean("IS_DEALING", false);
            if (isDealing)
            {
                deal(false);
            }
        }
    }

    private void deal(boolean isNew)
    {
        final AlertDialog progressDialog = DialogManager.showAlertDialog(this, R.string.generic_dialog_title, R.string.plandetail_btn_deal_processdesc,
                new int[] { R.string.generic_dialog_btn_cancel }, new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(final DialogInterface parentDialog, int which)
                    {
                        // TODO Auto-generated method stub
                        DialogManager.showAlertDialog(PlanDetailActivity.this, R.string.generic_dialog_title, R.string.plandetail_btn_deal_canceldesc, new int[] { R.string.generic_dialog_btn_yes,
                                R.string.generic_dialog_btn_no }, new DialogInterface.OnClickListener()
                        {
                            @Override
                            public void onClick(DialogInterface dialog, int which)
                            {
                                // TODO Auto-generated method stub
                                if (which == DialogInterface.BUTTON_POSITIVE)
                                {
                                    mgr.removeUpdates(listener);
                                    GPSManager.addCurFileToQueue(PlanDetailActivity.this);
                                    parentDialog.dismiss();
                                    currenttime.setText("");
                                    longitude.setText("");
                                    latitude.setText("");
                                    listener = null;
                                }
                            }
                        }, true, false);
                    }
                }, false, true);
        if (isNew)
            GPSManager.resetManager();
        currenttime.setText(R.string.plandetail_btn_deal_process);
        longitude.setText(R.string.plandetail_btn_deal_process);
        latitude.setText(R.string.plandetail_btn_deal_process);
        listener = new LocationListener()
        {
            @Override
            public void onStatusChanged(String provider, int status, Bundle extras)
            {
                // TODO Auto-generated method stub
                currenttime.setText(R.string.plandetail_btn_deal_process);
                longitude.setText(R.string.plandetail_btn_deal_process);
                latitude.setText(R.string.plandetail_btn_deal_process);
            }

            @Override
            public void onProviderEnabled(String provider)
            {
                // TODO Auto-generated method stub
                currenttime.setText(R.string.plandetail_btn_deal_process);
                longitude.setText(R.string.plandetail_btn_deal_process);
                latitude.setText(R.string.plandetail_btn_deal_process);
            }

            @Override
            public void onProviderDisabled(String provider)
            {
                // TODO Auto-generated method stub
                currenttime.setText(R.string.plandetail_btn_deal_notopen);
                longitude.setText(R.string.plandetail_btn_deal_notopen);
                latitude.setText(R.string.plandetail_btn_deal_notopen);
            }

            @Override
            public void onLocationChanged(Location location)
            {
                // TODO Auto-generated method stub
                long times = location.getTime();
                double lon = location.getLongitude();
                double lat = location.getLatitude();
                currenttime.setText(DateUtilities.getFormatDate(new Date(times), "yyyy-MM-dd HH:mm:ss"));
                longitude.setText(lon + "");
                latitude.setText(lat + "");
                try
                {
                    GPSManager.writePlanToBinaryFile(PlanDetailActivity.this, item.planId, user.userId, lon, lat, times);
                } catch (IOException e)
                {
                    LogManager.logE(PlanDetailActivity.class, "write file failed.", e);
                    mgr.removeUpdates(this);
                    progressDialog.dismiss();
                    DialogManager.showAlertDialog(PlanDetailActivity.this, R.string.generic_dialog_title, R.string.plandetail_btn_deal_ioexception, new int[] { R.string.generic_dialog_btn_ok }, null,
                            true, false);
                    currenttime.setText("");
                    longitude.setText("");
                    latitude.setText("");
                    listener = null;
                }
            }
        };
        mgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, listener);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState)
    {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
        if (listener == null)
        {
            outState.putBoolean("IS_DEALING", false);
        } else
        {
            outState.putBoolean("IS_DEALING", true);
        }
    }

    @Override
    protected void onDestroy()
    {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (listener != null)
            mgr.removeUpdates(listener);
    }

}